<script setup>
import { Edit, Delete } from '@element-plus/icons-vue'
import { ref ,watch} from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'
import { computed } from 'vue'
import { useTokenStore } from '../../stores/token'
import { useUserInfoStore } from '../../stores/userInfo'
import {
  getByIdStuService,
  updateStudentAssService,
} from '../../api/studentAss'

const userInfoStore = useUserInfoStore()
import { getStudentByIdService} from '../../api/student'
import { getByIdAssignmentService} from '../../api/assignment'
const searchQuery = ref('') // 新增的搜索条件

const filteredAsss = computed(() => {
  return studentAsss.value.filter(studentAss =>
    studentAss.info.includes(searchQuery.value)
  )
})

const studentAsss = ref([])

const title = ref('')
const imageUrl = ref('');
const dialogVisible = ref(false)
const fileName = ref(''); // 新增：用于存储文件名
// 学生作业表单模型
const studentAssModel = ref({
  title: '',
  info: '',
  id: 0,
})
// 提取文件名和后缀
const extractFileName = (fileLink) => {
  const url = new URL('/api' + fileLink, window.location.origin);
  const params = new URLSearchParams(url.search);
  return params.get('fileName') || '未知文件名';
};

//显示学生作业列表信息
const studentAssList = async () => {
  const stuId = userInfoStore.userInfo.id; // 获取 stuId
  let res = await getByIdStuService(stuId)
  const studentAsssData = res.data;
  const Promises = studentAsssData.map(async (studentAss) => {
    const assignmentResponse = await getByIdAssignmentService(studentAss.assId);
    //const studentResponse = await getStudentByIdService(studentAss.stuId);
    studentAss.title = assignmentResponse.data.title; // 添加作业名字
    studentAss.overdue = studentAss.overdue === 1? '已截止' : '开放' // 作业是否截止
    return studentAss;
  });
  studentAsss.value = await Promise.all(Promises); // 等待所有请求完成
}

// 显示作业详情
const showAss = async (row) => {
  dialogVisible.value = true;
  title.value = '修改学生作业';
  studentAssModel.value = { ...row }; // 先复制所有属性

  // 如果有文件链接，尝试获取图片并设置到 imageUrl
  if (studentAssModel.value.file) {
    try {
      const response = await fetch('/api' + studentAssModel.value.file, {
        headers: {
          Authorization: `${useTokenStore().token}`,
        },
      });
      if (!response.ok) throw new Error('Network response was not ok');
      const blob = await response.blob();
      imageUrl.value = URL.createObjectURL(blob);
      fileName.value = extractFileName(studentAssModel.value.file); // 设置文件名
    } catch (error) {
      console.error('Failed to load image:', error);
      imageUrl.value = ''; 
    }
  } else {
    imageUrl.value = ''; // 没有文件时清除 imageUrl
  }
};
//下载
const downloadFile = (fileLink) => {
  fetch('/api' + fileLink, {
    method: 'GET',
    headers: {
      'Authorization': `${useTokenStore().token}`, 
    }
  })
  .then(response => {
    return response.blob(); // 将响应转换为 Blob 对象
  })
  .then(blob => {
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.style.display = 'none';
    a.href = url;
    a.download= fileLink.split('/').pop(); // 指定下载的文件名和扩展名
    document.body.appendChild(a);
    a.click(); // 自动点击下载链接
    window.URL.revokeObjectURL(url); // 释放对象 URL
  })
  .catch(error => {
    console.error('出现问题', error);
  });
}
const handleImageError = () => {
  // 当图片加载失败时，将 imageUrl 设置为空字符串
  imageUrl.value = '';
};

// 提交作业
const submitAssignment = async () => {
  const res = await updateStudentAssService(studentAssModel.value);
  if (res.code === 0) {
    ElMessage.success('作业修改成功');
    dialogVisible.value = false;
    studentAssList();
  } else {
    ElMessage.error('作业修改失败');
  }
};

const handleSuccess = (response, file) => {
    console.log('文件上传成功:', response);
    if (response) {
      studentAssModel.value.file = response; // 将文件路径存入 assignmentModel
    }
}

const handleError = (err, file) => {
    console.error('文件上传失败:', err);
}
const handleRemove = (file, fileList) => {
    console.log('文件移除:', file);
    assignmentModel.value.file = ''; // 清除文件路径
    ElMessage.success('文件已成功移除');
}
//返回上一页
const goBack = () => {
  window.history.go(-1)
}
studentAssList()
</script>

<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <el-page-header @back="goBack">
          <template #content>
            <span>作业答卷</span>
          </template>
        </el-page-header>
        <el-input 
          v-model="searchQuery" 
          placeholder="搜索相关学生作业..." 
          style="width: 200px; margin-right: 10px;" 
        />
      </div>
    </template>

    <!-- 更新作业表单 -->
  <el-drawer v-model="dialogVisible"  title="作业详情" direction="rtl" size="40%">
    <el-form :model="studentAssModel" label-width="100px">
      <el-form-item label="作业标题">
        <el-input v-model="studentAssModel.title" style="width: 220px; " disabled></el-input>
      </el-form-item>
      <el-form-item label="作答内容">
        <el-input type="textarea"
        :rows="3" v-model="studentAssModel.info"  placeholder="请输入内容" style="width: 320px;"></el-input>
      </el-form-item>
      <el-form-item label="文件预览">
        <div v-if="studentAssModel.file" >
        <el-image 
          v-if="imageUrl"
          style="width: 200px; height: 200px"
          :src="imageUrl" 
          :preview-src-list="[imageUrl]"
          @error="handleImageError"
        >
        </el-image>
        <span>{{ fileName }}</span>
        <el-button @click="downloadFile(studentAssModel.file)" type="text">下载查看</el-button>
        </div>
        <div v-else>暂无文件</div>
      </el-form-item>
      <el-form-item label="上传文件">
        <el-upload
          ref="uploadRef"
          :auto-upload="true"
          class="upload-demo"
          drag
          action="/api/fileTwo/uploadceshi"
          :headers="{ 'Authorization': `${useTokenStore().token}` }"
          @success="handleSuccess"
          @error="handleError"
          @on-remove="handleRemove"
          :limit = "1"
        >
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="el-upload__text" style="width: 200px;">
           拖 拽 上 传 <em>点 击 选 择</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">
              jpg/png 文件不能超过 500kb
            </div>
          </template>
        </el-upload>
      </el-form-item>
      <input type="checkbox"><span style="color: #8d938d;font-size: 13px;">依照学术诚信条款，我保证此回答为本人原创，所有回答中引用的外部材料已经做了出处标记。</span>
      <p></p>
      <el-form-item>
        <el-button type="primary" @click="submitAssignment()">更新作业</el-button>
        <el-button >取消</el-button>
      </el-form-item>
    </el-form>
  </el-drawer>
    <!-- 列表 -->
    <el-table :data="filteredAsss" style="width: 100%">
      <el-table-column label="序号" width="70" type="index"></el-table-column>
      <el-table-column label="作业题目" prop="title" width="100"></el-table-column>
      <el-table-column label="提交时间" prop="createAt"></el-table-column>
      <el-table-column label="状态" prop="overdue"></el-table-column>
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button type="primary" plain  @click="showAss(row)">查看详情</el-button>
        </template>
      </el-table-column>
      <template #empty>
        <el-empty description="没有数据" />
      </template>
    </el-table>
  </el-card>
</template>

<style lang="scss" scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}
</style>
